<template>
  <div class="account-page">
    <!-- 新增个人实名信息展示区域 -->
    <!-- 个人实名信息区域 -->
    <section class="person-info">
      <h2>账号信息</h2>

      <!-- 加载/错误 -->
      <div v-if="personLoading" class="loading">加载中…</div>
      <div v-else-if="personError" class="error">{{ personError }}</div>

      <!-- 已认证 -->
      <div v-else-if="personAudit === '1'" class="info-card">
        <!-- <p><span class="label">姓名：</span>{{ person.name }}</p>
        <p><span class="label">身份证号：</span>{{ person.idCard }}</p>
        <p><span class="label">职位：</span>{{ person.role }}</p>
        <p><span class="label">认证状态：</span>{{ personAuditText }}</p>
        <p><span class="label">人脸状态：</span>{{ personFaceText }}</p>
        <p><span class="label">是否法人：</span>{{ person.isLegalPerson === "1" ? "是" : "否" }}</p>
        <p><span class="label">创建时间：</span>{{ person.createdAt }}</p> -->

        <div class="account-info-panel">
          <div class="info-column">
            <div class="column-header">当前登录账号信息</div>
            <div class="column-content">
              <div class="info-item">{{ phone }}</div>
              <div class="info-item">ID: {{ userId }}</div>
            </div>
          </div>

          <div class="info-column">
            <div class="column-header">账号角色</div>
            <div class="column-content">
              <div class="info-item">管理员</div>
              <div class="info-item">管理员可以对当前工作台组织进行管理相关操作,包括账户管理、子账号管理以及联系人信息管理。</div>
            </div>
          </div>

          <div class="info-column">
            <div class="column-header">联系人信息</div>
            <div class="column-content">
              <div class="info-item">
                {{ name }}
                <el-tag size="small" type="warning" class="auth-badge">
                  <img src="@/assets/images/certification.png" alt="实名认证" />
                  <span>实名认证</span>
                </el-tag>
              </div>
              <div class="info-item">
                <span>{{role}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 未实名 -->
      <div v-else-if="personAudit !== '1'" class="info-card">
        <!-- <p>您尚未完成个人实名认证。</p>
        <el-button type="primary" @click="openPersonAuthDialog" plain> 立即实名认证 </el-button> -->
        <div class="account-info-panel">
          <div class="info-column">
            <div class="column-header">当前登录账号信息</div>
            <div class="column-content">
              <div class="info-item">{{ phone }}</div>
              <div class="info-item">ID: {{ userId }}</div>
            </div>
          </div>

          <div class="info-column">
            <div class="column-header">账号角色</div>
            <div class="column-content">
              <div class="info-item"></div>
              <div class="info-item"></div>
            </div>
          </div>

          <div class="info-column">
            <div class="column-header">联系人信息</div>
            <div class="column-content">
              <div class="info-item">
                {{ name }}
                <el-tag size="small" type="warning" class="auth-badge-error">
                  <img src="@/assets/images/certificationErr.png" alt="未认证" />
                  <span>未认证</span>
                </el-tag>
                <p style="display: inline-block; margin: 0 10px; color: rgba(128, 128, 128, 1); font-size: 16px">请前往小程序完成实名认证。</p>
                <el-button type="primary" @click="openPersonAuthDialog" plain size="small" class="click-go"> 点击前往 </el-button>
              </div>
              <div class="info-item">
                <span v-if="role === '1'">销售</span>
                <span v-else-if="role === '2'">技术</span>
                <span v-else-if="role === '3'">采购</span>
                <span v-else-if="role === '4'">项目经理</span>
                <span v-else-if="role === '5'">总经理</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 二维码弹窗 -->
      <div class="qr-dialog">
        <el-dialog v-model="qrVisible" center :close-on-click-modal="false" :show-close="true" @closed="revokeQR">
          <div v-if="qrLoading" class="qr-loading">
            <el-icon class="is-loading" style="font-size: 24px; margin-right: 8px">
              <Loading />
            </el-icon>
            正在生成二维码...
          </div>
          <img v-else :src="qrBlobUrl" style="width: 315px; height: 321px; display: block; margin: auto auto" />
        </el-dialog>
      </div>
    </section>

    <!-- 企业认证弹窗 -->
    <CompanyAuthDialog />
    <!-- 企业信息（从接口获取） -->
    <section class="company-info">
      <h2>企业信息</h2>
      <div v-if="loading" class="loading">加载中…</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else-if="company" class="info-card">
        <!-- <p>
          <span class="label">主体信息：</span>
          {{ company.companyName }}
          <span class="verified">{{ auditStatusText }}</span>
        </p>
        <p><span class="label">统一社会信用代码：</span>{{ company.creditCode }}</p>
        <p><span class="label">认证日期：</span>{{ company.auditTime }}</p> -->
        <div class="account-info-panel">
          <div class="info-column">
            <div class="column-header">主体信息</div>
            <div class="column-content">
              <div class="info-item">
                {{ company.companyName }}

                <el-tag v-if="company.auditStatus === '1'" size="small" type="warning" class="auth-badge">
                  <img src="@/assets/images/certification.png" alt="实名认证" />
                  已认证
                </el-tag>
                <el-tag v-else-if="company.auditStatus === '2'" size="small" type="warning" class="auth-badge-Err">
                  <img src="@/assets/images/Err.png" alt="实名认证" />
                  认证失败
                </el-tag>
                <el-tag v-else-if="company.auditStatus === '0'" size="small" type="warning" class="auth-badge-Loading">
                  <img src="@/assets/images/Loading.png" alt="实名认证" />
                  认证中
                </el-tag>
                <el-tag style="margin: 0 10px" v-else size="small" type="warning" class="auth-badge-error">
                  <img src="@/assets/images/certificationErr.png" alt="实名认证" />
                  未认证
                </el-tag>
                <el-button v-if="company.auditStatus !== '1'" type="primary" @click="goCompanyAuth" plain size="small" class="click-go" style="margin-left: 15px">去认证</el-button>
              </div>
            </div>
          </div>

          <div class="info-column">
            <div class="column-header">统一社会信用代码</div>
            <div class="column-content">
              <div class="info-item">{{ company.creditCode }}</div>
            </div>
          </div>

          <div class="info-column">
            <div class="column-header">认证日期</div>
            <div class="column-content">
              <div class="info-item">{{ company.auditTime }}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import type {} from "element-plus";
import { ref, computed, onMounted, watch, onBeforeUnmount } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { Loading, CircleCloseFilled, CircleCheck } from "@element-plus/icons-vue";
import { getToken } from "@/utils/cache";
import { useRouter } from "vue-router";
import CompanyAuthDialog from "@/components/CompanyAuthDialog.vue";
import { isURL } from "@/utils/utils";

const router = useRouter();

const qrVisible = ref(false);
// ---- 响应式数据 ----
const loading = ref(false);
const error = ref("");
const company = ref<any>(null);
// --- 新增的响应式数据 ---
const person = ref<any>(null);
const personLoading = ref(false);
const personError = ref("");
// 二维码相关状态
const qrBlobUrl = ref("");
const qrLoading = ref(false);
const qrError = ref("");

// 用户手机号
const phone = ref("");
// 账号角色
const role = ref("");
// 联系人信息id
const userId = ref("");
// 联系人信息姓名
const name = ref("");
// 账户实名信息
const personAudit = ref("0");
let pollTimer: number | null = null;
/** 打开弹窗并拉取二维码 */
async function openPersonAuthDialog() {
  qrVisible.value = true;
  // await fetchQRCode();
  await getQrcodeFetch();
  // 启动轮询
  pollTimer = window.setInterval(async () => {
    await fetchPersonInfo(false);
    if (personAudit.value === "1") {
      // 已认证 → 关弹窗 + 停轮询
      qrVisible.value = false;
      clearInterval(pollTimer!);
      pollTimer = null;
      ElMessage.success("实名认证成功");
    }
  }, 3000);
}
// 弹窗关闭时清轮询
watch(qrVisible, (val) => {
  if (!val && pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
});
// 组件卸载时兜底
onBeforeUnmount(() => {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
});
async function getQrcodeFetch() {
  qrLoading.value = true;
  try {
    const blob = await baseService.get(
      "/noc/authcompanyaudit/getWxQrCode",
      {
        userId: userId.value,
        jumpType: 1
      },
      {},
      { responseType: "blob" }
    );

    qrBlobUrl.value = URL.createObjectURL(blob);
  } catch (error) {
    // 错误处理
    console.error("获取微信二维码失败：");
  } finally {
    qrLoading.value = false;
  }
}
function revokeQR() {
  if (qrBlobUrl.value) {
    URL.revokeObjectURL(qrBlobUrl.value);
    qrBlobUrl.value = "";
  }
}

// ---- 计算属性 ----
const auditStatusText = computed(() => {
  switch (company.value?.auditStatus) {
    case "0":
      return "未认证";
    case "1":
      return "已认证";
    default:
      return "";
  }
});
// --- 新增的计算属性 ---
const personAuditText = computed(() => {
  switch (person.value?.audit) {
    case "0":
      return "未认证";
    case "1":
      return "已认证";
    case "2":
      return "审核中";
    case "3":
      return "审核失败";
    default:
      return "";
  }
});
const personFaceText = computed(() => {
  switch (person.value?.faceStatus) {
    case "0":
      return "未采集";
    case "1":
      return "已采集";
    default:
      return "";
  }
});
// --- 新增方法 ---
async function fetchPersonInfo(load: any) {
  if (load) {
    personLoading.value = true;
  }
  personError.value = "";
  try {
    const res = await baseService.get("/noc/authpersonaudit/getPersonInfo");
    if (res.code === 0) {
      console.log(res, "res");
      phone.value = res.data.phone;
      role.value = res.data.role;
      userId.value = res.data.userId;
      name.value = res.data.name;
      personAudit.value = res.data.audit;
      // console.log(personAudit.value, 'person.value');
    } else {
      personError.value = res.msg || "获取个人实名信息失败";
    }
  } catch (e: any) {
    personError.value = e.message || "网络错误";
  } finally {if (load) {
    personLoading.value = false;
  }
  }
}
// ---- 生命周期 ----
onMounted(() => {
  fetchCompanyStatus();
  fetchPersonInfo(true);
});

// ---- 方法 ----
// 获取企业认证状态
async function fetchCompanyStatus() {
  loading.value = true;
  error.value = "";
  try {
    const res = await baseService.get("/noc/authcompanyaudit/getStatus");
    if (res.code === 0) {
      console.log(res, "res-company");
      company.value = res.data;
      // step 为 0 表示未认证
    } else {
      error.value = res.msg || "获取企业信息失败";
    }
  } catch (e: any) {
    error.value = e.message || "网络错误";
  } finally {
    loading.value = false;
  }
}
// 企业认证实名认证
function goCompanyAuth() {
  // state.closeCurrentTab();cnas/certification-process
  // router.replace("/cnas/certification-process");
  router.replace("/cnas/certification-results");
}
</script>

<style scoped lang="scss">
.account-page {
  width: 100%;
  margin: 0px auto;
  padding: 0 16px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  color: #333;
}

section {
  margin-bottom: 32px;
}

h2 {
  margin-top: 0px;
  font-size: 17px;
  font-weight: 500;
  letter-spacing: 0px;
  // line-height: 32px;
  color: rgba(56, 56, 56, 1);
  text-align: left;
  vertical-align: top;
  background: rgba(242, 242, 242, 1);
  padding: 4px 15px;
  margin-bottom: 20px;
}

.info-card {
  // background: #fff;
  // border: 1px solid #e5e5e5;
  // border-radius: 8px;
  // padding: 20px;
  // line-height: 1.8;

  .label {
    display: inline-block;
    width: 180px;
    color: #666;
  }

  .verified {
    color: #00b33c;
    font-weight: 600;
  }

  .tip {
    margin-top: 12px;
    font-size: 14px;
    color: #888;
    line-height: 1.6;
  }
}

.loading,
.error {
  padding: 20px;
  text-align: center;
  color: #666;
}

.error {
  color: #ff4d4f;
}

.qr-loading,
.qr-error {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
  font-size: 16px;
}

.qr-error {
  color: #f56c6c;
}

.account-info-panel {
  display: flex;
  background: #fff;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  overflow: hidden;
}

.info-column {
  flex: 1;
  // border-right: 1px solid #e5e5e5;

  &:last-child {
    border-right: none;
  }
}

.column-header {
  background: rgba(239, 244, 255, 1);
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 0px;
  line-height: 23.17px;
  color: rgba(56, 56, 56, 1);
  text-align: left;
  padding: 10px 20px;
  // border-bottom: 1px solid #e5e5e5;
}

.column-content {
  padding: 10px 20px;
  // min-height: 120px;
}

.info-item {
  font-size: 16px;
  line-height: 22px;
  color: rgba(56, 56, 56, 1);
  text-align: left;
  vertical-align: top;
  margin-bottom: 10px;
}

// .info-description {
//   font-size: 12px;
//   color: #666;
//   line-height: 1.6;
//   margin-top: 8px;
// }

.auth-badge,
.auth-badge-error,
.auth-badge-Err,
.auth-badge-Loading {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  border-radius: 0px;
  background: rgba(255, 223, 189, 0.7);
  color: rgba(252, 130, 0, 1);
  // margin-top: -3px;
  padding: 0px 5px;

  img {
    width: 11px;
    height: 13px;
    margin-right: 4px;
    vertical-align: middle;
  }

  span {
    vertical-align: middle;
  }
}

.auth-badge{
  img{
    margin-top: -5px;
  }
}

.auth-badge-error {
  background: rgba(214, 214, 214, 0.7);
  color: rgba(128, 128, 128, 1);
}

.auth-badge-Err {
  background: rgba(255, 217, 217, 0.7);
  color: rgba(255, 0, 0, 1);
}

.auth-badge-Loading {
  background: rgba(239, 244, 255, 1);
  color: rgba(22, 119, 255, 1);
}

.qr-dialog {
  // width: 500px;

  :deep(.el-dialog) {
    background-color: pink;
    width: 500px;
  }

  :deep(.el-dialog__header) {
    width: 500px;
    height: 174px;
    background-image: url("@/assets/images/bgimg.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: 0 0;
    color: #fff;
  }

  :deep(.el-dialog__body) {
    width: 500px;
    height: 360px;
    background-color: #ffffff;
    padding: 20px;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    font-size: inherit;
    color: #fff !important;
  }
}
.click-go {
  margin-top: 8px;
  font-size: 15px;
  width: 100px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(239, 244, 255, 1);
  border: 1px solid rgba(22, 119, 255, 1);
  color: rgba(22, 119, 255, 1);
}
</style>
